package com.aizuda.easyManagerTool.service.monitor.impl;

import cn.hutool.core.util.ObjectUtil;
import com.aizuda.easyManagerTool.domain.entity.monitor.MonitorUrlEntity;
import com.aizuda.easyManagerTool.util.AssertUtil;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Data
public class MonitorListManager {

    private static Map<Integer,MonitorData> indexMap = new ConcurrentHashMap<>();


    public static MonitorData getAndPut(Integer id,MonitorData data){
        AssertUtil.objIsNull(id,"id 不能为空");
        AssertUtil.objIsNull(data,"指标集不能为空");
        return indexMap.computeIfAbsent(id, key -> data);
    }

    public static void remove(Integer id){
        indexMap.remove(id);
    }

    public static void putIndex(Integer id,MonitorDataIndex dataIndex){
        if(ObjectUtil.isEmpty(dataIndex.getId())){
            return;
        }
        AssertUtil.objIsNull(id,"id 不能为空");
        AssertUtil.objIsNull(dataIndex,"指标不能为空");
        List<MonitorDataIndex> indexList = indexMap.get(id).getDataIndex();
        Optional<MonitorDataIndex> any = indexList.stream()
                .filter(item -> item.getId().equals(dataIndex.getId())).findAny();
        // 找到则替换
        if (any.isPresent()) {
            indexList.remove(any.get());
        }
        indexList.add(dataIndex);
    }

    public static void removeIndex(Integer id){
        indexMap.keySet().stream().forEach(item -> {
            List<MonitorDataIndex> dataIndex = indexMap.get(item).getDataIndex();
            Optional<MonitorDataIndex> any = dataIndex.stream().filter(di -> di.getId().equals(id)).findAny();
            any.ifPresent(dataIndex::remove);
        });
    }

    public static List<MonitorData> getValues(){
        return indexMap.values().stream().collect(Collectors.toList());
    }

    public static MonitorData getIndexItem(Integer id){
        AssertUtil.objIsNull(id, "id 不能为空");
        return indexMap.get(id);
    }

    @Data
    public static class MonitorData{

        private Integer id;

        List<MonitorUrlEntity> urls;

        private Integer tenantId;

        private List<MonitorDataIndex> dataIndex = new ArrayList<>();

        private Map<String, Object> json;
    }

    @Data
    public static class MonitorDataIndex{

        private Integer id;

        private String name;

        private String exp;

        private String value;

        private String time;

        private String threshold;

        private Integer frequency;

        private Integer currentFrequency = 0;

        private String fullName;

        private Boolean mdiAlarm = false;

    }

}
